<?php
/**
 * 违规单管理
 *  
 */ 
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;
use Common\ORG\Page,Common\ORG\AttUpload,Common\ORG\Excel;

class ViolationsController extends BaseController {
	//首页
	public function index(){
		$arr = D("FineUser")->violationsIndex($_GET,$this->m_psize);
		e_json($arr);
	}
	//违规添加信息加载
	public function addShow(){
    $res['today']    = date("Y-m-d");
		e_json($res);
	}
	
	//添加违规信息
	public function violationsAdd(){
		$contract = I("contract");
		if(!empty($contract)){
			$res = D("FineUser")->violationsAdd($_GET);
		}else{
			$res['rcode'] = 2;
			$res['msg']   = "暂没有关联合同信息,添加失败!";
		}
		e_json($res);
	}
  //编辑加载
  public function editor_show(){

    //当前违规合同信息
    $Id = I("fine_id");
    //未违规的合同信息
    $where['contract.customer_id'] = I("customer_id");
    $where['contract.is_delete']   = array("neq",'1');
    $where['contract.state']       = array(array('eq','0'),array('eq','1'),array('eq','4'),'or');
    // $where['contract.weigui_status'] = array(array('neq','11'),array('neq','12'),array('neq','21'),'and');
    $contract = M("contract")
               ->field("product.name,user.nickname,contract.order_num,contract.sales_person,contract.contract_id,contract.mount,contract.state,contract.weigui_status")
               ->join("LEFT JOIN product ON contract.product_id    = product.product_id")
               ->join("LEFT JOIN user    ON contract.sales_person  = user.user_id")
               ->where($where)
               ->order("contract.contract_id desc")
               ->limit(0,5)
               ->select();
    foreach ($contract as $key => $value) {
      if($value['weigui_status'] == 0){
        $list[] = $value;
      }
    }

    $maps['contract.contract_id'] = I("contract_id");
    $arr[0] = M("contract")
               ->field("product.name,user.nickname,contract.order_num,contract.sales_person,contract.contract_id,contract.mount,contract.state,contract.weigui_status")
               ->join("LEFT JOIN product ON contract.product_id    = product.product_id")
               ->join("LEFT JOIN user    ON contract.sales_person  = user.user_id")
               ->where($maps)
               ->find();
    if($arr && !empty($list)){
      $list = array_merge($list,$arr);
    }elseif($arr && empty($list)){
      $list = $arr;
    }

    if(!$list){
      $res['list'] = "没有找到相关有效不违规的合同!!!";
    }else{
      $res['rcode'] = 1;
      $res['list'] = $list;
    }
    e_json(  $res );
  }
  //编辑
  public function violationsEditor(){
    $where['fine_id'] = I("post.fine_id");
    $history = M("fine")->field("fine_id,contract_id")->where($where)->find();

    $contract = I("post.contract_id");
    if($history['contract_id'] != $contract && !empty($contract)){
      $map['contract_id'] = $contract;
      $check_fine= M("fine")->field("fine_id,contract_id")->where($map)->find();
      if($check_fine){
        $res['error'] = 1;
        e_json($res);
      }
    } 
    $theme       = I('post.theme');
    $performance = I("post.performance");
    $note        = I("post.note");
    $pub_time    = I("post.pub_time");
    $money       = I("post.editor_money");

    if(!empty($note) && !empty($performance))     $map['remark'] = $performance.','.$note;
    elseif(!empty($note) && empty($performance))  $map['remark'] = $note;
    elseif(empty($note) && !empty($performance))  $map['remark'] = $performance;
    else  $map['remark']  = '';
    
    $map['theme']     = $theme ;
    $map['pub_time']  =     $pub_time;
    $map['update_time'] = date("Y-m-d H:i:s");

    $fine = M("fine")->where($where)->save($map);

    if($history['contract_id'] != $contract &&  $fine && !empty($contract)){
      //合同违规变更
      $no_weigui['contract_id'] = $history['contract_id'];
      $weigui_case['weigui_status'] = 0;
      $update1 = M("contract")->where($no_weigui)->save($weigui_case);
      
      $save_weigui['contract_id'] = $contract;
      $weigui_case2['weigui_status'] = 12;
      $update2 = M("contract")->where($save_weigui)->save($weigui_case2);
    }
  
    $fine_user = M("fine_user")->field("fine_user_id,fine_mount")->where($where)->order("fine_user_id desc")->find();
    if($fine_user){
       if($fine_user['fine_mount'] != $money ){
          $wheres['fine_user_id'] = $fine_user['fine_user_id'];
          $maps['fine_mount'] = $money;
          $arr = M("fine_user")->where($wheres)->save($maps); 
      }else{
        $arr  = $fine; 
      }
    }else{
      $message = M("contract")->field("sales_person,sales_manager,sales_sector,sales_sub_company")->where($where)->find();
      $maps['fine_id']     = $history['fine_id'];
      $maps['fine_type']   = 1;
      $maps['fine_mount']  = $money;
      $maps['fine_remark'] = '';
      $maps['is_delete']   = 0;

      $maps['sales_id']           = $message['sales_person'];
      $maps['sales_sector']       = $message['sales_sector'];
      $maps['sales_manager']      = $message['sales_manager'];
      $maps['sales_subcompany']   =$message['sales_sub_company'];

      $arr = M("fine_user")->add($maps); 
    }
   
    if($arr){
      $res['rcode'] = 1;
    }else{
      $res['msg']   = "修改失败!!!"; 
    }
    e_json($res);
  }
	//违规取消
	public function cancel(){
		$where['fine_id'] = I("fine");
		$map['status']    = 2;
		$fine = M("fine")->where($where)->save($map);
		if($fine){
			$wheres['contract_id'] = I("contract");
			$state['weigui_status'] =  21;
      $check = M("contract")->field("weigui_status")->where($wheres)->find();
      if($check['weigui_status'] !=21){
        $contract = M("contract")->where($wheres)->save($state);  
        if(!$contract){
          $undo['status']  = 1;
          M("fine")->where($where)->order("fine_id desc")->save($undo);
        }
      }
      $res['rcode'] = 1;
		}else{
      $res['Msg'] = "修改失败!!!";
    }
		e_json($res);
	}
	//导出违规记录
  public function export_excel(){
  	 //搜索条件
  	  $customer = I('customer');
      if(!empty($customer)){
          if(strlen($customer) > 3 && is_numeric($customer))  $map['customer.phone'] = array('like','%'.$customer.'%');
          $map['customer.nickname']       = array('like','%'.$customer.'%');
          $map['customer.customer_code']  = array('like','%'.$customer.'%');
          $map['_logic']          = 'or';
          $where['_complex'] = $map;
      }
      $saless   = I('get.sales','','trim');
      if($saless){
          $where['user.nickname']  = array('like','%'.$saless.'%');
      }

      //区间与时间检索
        $stime    = I('get.first_time','','trim');
        $etime    = I('get.second_time','','trim');
        if($stime && $etime){
            $time1 = date("Y-m-d 00:00:00",strtotime($stime));
            $time2 = date("Y-m-d 23:59:59",strtotime($etime));
            if(strtotime($time1) < strtotime($time2)) $where['fine.pub_time'] =  array('between', array($time1, $time2 ) );
            else $where['fine.pub_time'] =  array('between', array( $time2 ,$time1) );
        }elseif($stime && !$etime){
            $time =  date("Y-m-d 00:00:00",strtotime($stime));
            $where['fine.pub_time'] = array('egt', $time );
        }elseif(!$stime && $etime){
            $time = date("Y-m-d 23:59:59",strtotime($etime));
            $where['fine.pub_time'] = array('elt', $time );
        }
      $where['fine.fine_type'] = 2;
      //采集数据
      if(isset($_GET['default'])){
        $res = "";
      }else{
        $res = M("contract")
               ->field("contract.order_num,contract.mount,contract.start_time,contract.sales_person,contract.sales_manager,contract.sales_sub_company,customer.nickname as customer_name,fine.theme,fine.contract_id,fine_id")
              ->join("LEFT JOIN fine      ON contract.contract_id = fine.contract_id ")
              ->join("LEFT JOIN customer  ON contract.customer_id = customer.customer_id ")
              ->join("LEFT JOIN user      ON contract.sales_person = user.user_id ")
              ->where($where)
              ->order("fine.update_time desc")
              ->select();
      }      
      import("Common.ORG.Excel");
      $SExcel = new \Common\ORG\Excel();
      $SSheet = new \Common\ORG\Sheet("违规记录");

      $headline = array('合同编号','违规业绩客户','违规金额(元)','合同开始时间','业务员','经理','团队','违规原因');
      $SSheet->setColumn( $headline );
      foreach ($res as &$value) {
        $wheres['fine_id'] = $value['fine_id'];
        $fine_user = M("fine_user")->field("fine_mount")->where($wheres)->find();
        //负责人
        $sales['user_id']   = $value['sales_person'];
        $user    = M("user")->field("nickname")->where($sales)->find();
        //经理
        $sector['user_id']  = $value['sales_manager'];
        $manager = M("user")->field("nickname")->where($sector)->find();
        //团队
        $team['sector_id']  = $value['sales_sub_company'];
        $company = M("sector")->field("sector_name")->where($team)->find(); 

        $row     = array();
        $row[]   = $value['order_num'];
        $row[]   = $value['customer_name'];
        $row[]   = floor($fine_user['fine_mount']);
        $row[]   = date("Y-m-d",strtotime($value['start_time']));
        $row[]   = $user['nickname'];
        $row[]   = $manager['nickname'];
        $row[]   = $company['sector_name'];
        $row[]   = $value['theme'] == 1 ? '不签署合同':($value['theme']==2?'暂不寄':($value['theme']==3?'超龄':'虚假信息'));
        $SSheet->addRow( $row );
      }
 
      $exportData = $SExcel->add_sheet( $SSheet)->export_sheet("违规数据记录表");
      if( $exportData['rcode'] ){
        $exportData['name'] = basename( $exportData['data']['view_path'] );
        $exportData['excel'] = file_get_contents( $exportData['data']['real_path'] );
        echo $exportData['excel'];
        exit();
      }
  }
  //自动补全查找客户
  public function violationsCustomer(){

    $message = I("get.message");
    $where = array();
    if(strlen($message) > 4 && is_numeric($message) == true)
      $where['customer.phone'] = array('like','%'.$message.'%');
    else
      $where['customer.nickname'] = array('like','%'.$message.'%');

      $where['customer.is_delete'] = 0;
      $where['customer.state']     = 1; 

      $customer = M("customer")
                ->field("customer.customer_id,customer.nickname,customer.phone,customer.mount,customer.remark,customer.location,customer.state,customer.sales_sector,user.user_id,user.nickname as user_name")
                ->join("LEFT JOIN user ON customer.sales_person = user.user_id") 
                ->where($where)
                ->select();  
      foreach ($customer as $key => $value) {
        //关联的合同
          $wheres['contract.is_delete']     = array("neq",'1');
          $wheres['contract.customer_id']   = $value['customer_id'];
          $wheres['contract.state']         = array(array('eq','0'),array('eq','1'),array('eq','4'),'or');
          $wheres['contract.weigui_status'] = array('eq','0');
          $customer[$key]['child'] = M("contract")
                                   ->field("product.name,user.nickname,contract.order_num,contract.sales_person,contract.sales_sector,contract.contract_id,contract.mount,contract.state,contract.start_time,contract.weigui_status,contract.sales_sub_company,contract.sales_manager")
                                   ->join("LEFT JOIN product ON contract.product_id    = product.product_id")
                                   ->join("LEFT JOIN user    ON contract.sales_person  = user.user_id")
                                   ->where($wheres)
                                   ->order("contract.contract_id desc")
                                   ->limit(0,5)
                                   ->select();
          // $customer[$key]['find']  = M("fine")->select(); 
          $customer[$key]['mount'] =  floor($customer[$key]['mount']);  
      }
      if($customer){
        $res['customer'] = $customer;
        $res['rcode'] = 1;
      } 
      else
        $res['msg'] = "没有找到相关人员!!!"; 
      e_json($res);
  }
  //自动补全检验
  public function violations_check(){
    $nickname = I("nickname",'','trim');
    if($nickname)
       $where['nickname'] =  $nickname;
    else
       $where['customer_id'] = I("customer_id");
   
    $customer = M("customer")->field("customer_id,nickname")->where($where)->find();
    if($customer){
      $res['rcode'] = 1;
      $res['customer_check'] = $customer; 
    }else{
      $res['rcode'] = 2;
    }
    e_json($res);
  }
  //导入违规单
  public function import_excel(){
    $uinfo = D("FineUser")->User();
    if( IS_POST ){
      $fname  = I('post.name','file', 'trim');
      $newDir = I('post.newname','','trim');
      $Mdo    = new AttUpload();
      $MExcel = new Excel();
      $realpath = '';
      //Excel文件上传
      $ret = $Mdo->http_upload( $fname, $newDir);
      if ($ret && (1 != $ret['rcode'])) {
        $res['msg']   = $ret['msg'];
        e_json( $res );
      }else{
        $realpath = $ret['data']['view_path'];
      }
    
      //Excel 解析
      $excelData = $MExcel->parse_file(  $realpath );
     
      //数据写入数据库
      foreach ($excelData['data']['row']['s0'] as $key => $value) {
        $where['order_num'] = $value[0];
        $contract = M("contract")->field("contract_id")->where($where)->find();
        if($contract){
          $map['contract_id'] = $contract['contract_id'];
          $check_fine = M("fine")->where($map)->find();
          if(!$check_fine){
           
            if($values[7] == '暂不寄')   $map['theme'] = 2;
            if($values[7] == '超龄')     $map['theme'] = 3;
            if($values[7] == '虚假信息') $map['theme'] = 4;
            else  $map['theme']  = 1;

            $map['fine_num']     = '';
            $map['title']        = '';
            $map['description']  = '';
            $map['reply_action'] = '';
            $map['pub_time']     = date("Y-m-d H:i:s");
            $map['fine_type']    = 2;
            $map['contract_id']  =  $contract['contract_id'];
            $map['show_way']     = '';
            $map['status']       = 1;
            $map['update_time']  = date("Y-m-d H:i:s");
            $map['creator']      = $uinfo['user_id'];
            $map['remark']       = '';
            $map['is_delete']    = '';
            $add[] = M("fine")->add($map);

          }else{
            $exit[]  = $value[0];//已存在的数据
          }
        }else{
          //合同编号不正确
          $matching[]     = $value[0];
        }
      }
      if($matching){
        $res['invalid'] = implode('、',$matching);
      }

      //数据统计
      $res['statistical']['sum']        = count($excelData['data']['row']['s0']);//上传总数
      $res['statistical']['repeat']     = count($exit);//重复数据
      $res['statistical']['matching']   = count($matching); //不匹配数据
      $res['statistical']['successful'] = count($add); //成功数据
      e_json($res);  
    }
  }
}